import LoadUtil from './LoadUtil';
import GameConfig from '../../Server/Data/GameConfig';
import StorageCenter from '../../Server/StorageCenter';

/**
 * 用途         :游戏内<定制>的方法 可能不通用
 * 开发者       :郑品延
 * 修改时间     :2019/8/6
 */
export default class GameUtil {
    public static openBookId = 11;       //当前打开书本
    public static currPkLevel = 1;      //当前竞技场等级
    //---------------------------跳转场景-----------------------
    public static setOpenBookId(number){
        this.openBookId = number
        Log("当前打开的书：",this.openBookId);
    }
    public static sceneName = '';
    static isLoadScene = false;
    public static async gotoScene(name, func?,isLoad?) {
        let node = await LoadUtil.loadPrefabFunc('LoadPage');
        node.parent = cc.find('Canvas');
        let onProgress = (completedCount, totalCount, item)=>{
            node.getChildByName('ProgressBar').getComponent(cc.ProgressBar).progress = completedCount/totalCount;
            // node.getChildByName('Label').getComponent(cc.Label).string = Math.floor(completedCount/totalCount * 100) + "%";
        }
        if (func) {
            if (isLoad){
                let time = new Date().getTime();
                GameUtil.isLoadScene = true;
                let back = ()=>{
                    GameUtil.isLoadScene = false;
                    func();
                }
                // cc.director.loadScene(name,back);
                cc.director.preloadScene(name,onProgress,()=>{
                    let cTime = new Date().getTime();
                    let dis = cTime - time;
                    if (dis > 1000){
                        cc.director.loadScene(name,back);
                        // node.destroy();
                    }
                    else{
                        setTimeout(()=>{
                            cc.director.loadScene(name,back);
                            // node.destroy();
                        },1000 - dis);
                    }
                })
            }
            else{
                cc.director.loadScene(name,func);
            }
        }
        else {
            if (isLoad){
                let time = new Date().getTime();
                GameUtil.isLoadScene = true;
                let back = ()=>{
                    GameUtil.isLoadScene = false;
                }
                // cc.director.loadScene(name,back);
                cc.director.preloadScene(name,onProgress,()=>{
                    let cTime = new Date().getTime();
                    let dis = cTime - time;
                    if (dis > 1000){
                        node.destroy();
                        cc.director.loadScene(name,back);
                    }
                    else{
                        setTimeout(()=>{
                            node.destroy();
                            cc.director.loadScene(name,back);
                        },1000 - dis);
                    }
                })
            }
            else{
                cc.director.loadScene(name);
            }
        }
        GameUtil.sceneName = name;
    }
    public static reloadScene() {
        cc.director.loadScene(GameUtil.sceneName);
    }
    public static showStarNum(starArray,num){
        for(let i =0 ;i<starArray.length;i++){
            starArray[i].active = num > i;
        }
    }
    public static isTooth = false;
    //-------------------------------------------------------------------------------------
    public static updateDay() {           //用来判断是否更新本地以天为基础的,签到,抽奖等
        var day = ReadLocal('lastDay', 'null');
        var mydate = new Date();
        var tday = mydate.getDate();
        if (day == 'null') {
            SaveLocal('lastDay', tday + '');
            //这里和下面那里可以填每天刷新的数值
            //此时第一次登陆,算登陆1天
            StorageCenter.setUserContinueLogin(1);
        }
        else {
            if (tday != parseInt(day)) {
                SaveLocal('lastDay', tday + '');

               //这里和上面那里可以填每天刷新的数值

               //此时计算当前天的上一天是几号
               mydate.setDate(mydate.getDate()-1);
               let lday = mydate.getDate();
               Log('当前天:',tday,'缓存的上一天:',day,'计算的上一天:',lday);
               if (lday == parseInt(day)){
                   StorageCenter.addUserContinueLogin();
               }
               else{
                    StorageCenter.setUserContinueLogin(1);
               }
            }
        }
    }
    //用来判断倒计时回入场券
    public static timeDown = '05:00';
    public static didadida = null;
    /**
     * 开启倒计时计算体力
     */
    public static updateDate(){
        this.computerDate();
        if (!this.didadida){
            this.didadida = setInterval(()=>{
                let str = this.computerDate();
                if (str != 'new'){
                    this.timeDown = this.computerDate();
                }
            },1000)
        }
    }
    public static computerDate(){
        let lastTime = parseInt(ReadLocal('lastTime','null'));
        let currDate = new Date();
        let mydate = currDate.getTime();
        if (isNaN(lastTime)){
            SaveLocal('lastTime', mydate);
            return 'new';
        }
        else{
            let gap = Math.floor((mydate - lastTime)/1000); //单位是毫秒 除以1000获得秒
            let replySecond = GameConfig.replyTime * 60;
            let divisor = gap / replySecond;
            let remainder = gap % replySecond;
            let max = GameConfig.staminaMax;
            if (divisor >= 1){       //说明超过了30分钟 要加入场券了
                let addNum = Math.floor(divisor);
                let stamina = StorageCenter.getUserStamina();
                if (stamina < max){
                    if (addNum + stamina > max){
                        addNum = max - stamina;
                    }
                    StorageCenter.addUserStamina(addNum);
                }
                let newDate = new Date(mydate - remainder);
                SaveLocal('lastTime', newDate.getTime());
            }
            if (StorageCenter.getUserStamina() < max){
                let str = this.showCountdown(remainder);
                return str;
            }
            else{
                return '已满';
            }
        }
    }
    public static showCountdown(remainder){
        let str = '';
        let minStr = '';
        let secStr = '';
        let minute = Math.floor(remainder/60);
        let second = remainder%60;
        if(minute >= 10)
            minStr = '' + minute;
        else{
            minStr = '0' + minute;
        }
        if(second >= 10)
            secStr = '' + second;
        else{
            secStr = '0' + second;
        }
        str = minStr + ':' + secStr;
        return str;
    }
    public static levelToGuanqia(level){
        let x = Math.floor((level-1)/5)+1;
        let y = (level-1)%5+1;
        return x+'-'+y;
    }
    public static timestampToStr(timer,splitStr:string = '/'):string{
        let t = parseInt(timer);
        if (isNaN(t)){
            return '';
        }
        let sDate = new Date(t);
        let year = String(sDate.getFullYear());
        let month = String(sDate.getMonth()+1).padStart(2,'0');
        let day = String(sDate.getDate()).padStart(2,'0');
        let hour = String(sDate.getHours()).padStart(2,'0');
        let minute = String(sDate.getMinutes()).padStart(2,'0');
        let timeStr = `${year}${splitStr}${month}${splitStr}${day} ${hour}:${minute}`;
        return timeStr;
    }
}
